
#if 1
#include "Card.h"
#include "CardPrivate.h"
#include "Contactless/ISO14443p3b.h"
#include "CardCpuPrivate.h"

#include "Mem.h"

//	static CpuCard_T cpuCardB;
static const CpuCardOps_T cpuCardBOps;
//	static ISO14443BInfo_T cardInfo;

static void Card_CpuB_Init(Card_T* card, WCI* wci, void *pdata) {
	card->type = Card_T_CpuB;
	card->wci = wci;
	card->ops = &cpuCardBOps;
	card->pdata = pdata;
}

static Card_T* Card_CpuB_Create(WCI* wci) {

	Card_T* card = (Card_T*)Memory_Alloc(sizeof(CpuCard_T));
	if(card){
		ISO14443BInfo_T* info = (ISO14443BInfo_T*)Memory_Alloc(sizeof(ISO14443BInfo_T));
		if(info){
			Card_CpuB_Init(card, wci, (void*)info);
		}
		else{
			Memory_Free(card);
			card = (Card_T*)0;
		}
	}
	return card;
}

static void Card_CpuB_Destroy(Card_T* card) {
	if(card){
		Memory_Free(card->pdata);
		Memory_Free(card);
	}
}

const CardFactory_T cpuCardFactoryB = {
	.init = Card_CpuB_Init,
	.create = Card_CpuB_Create,
	.destroy = Card_CpuB_Destroy,
};

static int Card_CpuB_Probe(Card_T* card) {
	ISO14443BInfo_T info;
	int ret = ISO14443B_RequsetB(card->wci, &info);
	return ret == WCI_S_OK || ret == WCI_S_Coll;
}

static int Card_CpuB_Activate(Card_T* card) {
	int ret = ISO14443B_Activate(card->wci, PICC_Op_Request, (ISO14443BInfo_T*)card->pdata);
	if (ret == 0) {
		card->state = 1;
	}
	return ret;
}

static int Card_CpuB_Deactivate(Card_T* card) {
	ISO14443BInfo_T* info = (ISO14443BInfo_T*)card->pdata;
	int ret = ISO14443B_HaltB(card->wci, &info->atqb[1]);
	card->state = 0;
	return ret;
}

static int Card_CpuB_Exchange(Card_T* card, 
	unsigned char capdu[], unsigned int clen, unsigned char rapdu[], unsigned int* rlen) {
	CpuCard_T* cpuCard = (CpuCard_T*)card;

	return ISO14443p4_Exchange(cpuCard, capdu, clen, rapdu, rlen);
}

static int Card_CpuB_Setup(Card_T* card, uint8_t cid, uint8_t fsdi, void *param, uint8_t ats[]) {
//		CpuCard_T* cpuCard = (CpuCard_T*)card;
	ISO14443BInfo_T* info = (ISO14443BInfo_T*)param;
	uint8_t* pupi = &info->atqb[1];
	unsigned char resp[16];
	unsigned int rlen;
	int ret = ISO14443B_ATTRIB(card->wci, pupi, cid, resp, &rlen);
	if (ret) {
		return ret;
	}
	card->state = 2;
	return ret;
}

static int Card_CpuB_Teardown(Card_T* card) {
	CpuCard_T* cpuCard = (CpuCard_T*)card;
	int ret = ISO14443p4_Deselect(cpuCard);
	card->state = 0;
	return ret;
}

static int Card_CpuB_Check(Card_T* card){
	return ISO14443_CheckPresence((CpuCard_T*)card);
}


static const CpuCardOps_T cpuCardBOps = {
	.probe = Card_CpuB_Probe,
	.activate = Card_CpuB_Activate,
	.deactivate = Card_CpuB_Deactivate,
	.exchange = Card_CpuB_Exchange,
	.setup = Card_CpuB_Setup,
	.teardown = Card_CpuB_Teardown,
	.check = Card_CpuB_Check
};
#endif 

